package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ItemClient itemClient;

    @Override
    public void createIndexAndMapping() {
        try {
            this.goodsRepository.deleteIndex();
        } catch (Exception e) {
        }
        this.goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }

    /**
     * goods对象的生成
     * @param spuDTO
     * @return
     */
    public Goods buildGoods(SpuDTO spuDTO){
        Goods goods = new Goods();
        BeanUtils.copyProperties(spuDTO,goods);

        //categoryId
        goods.setCategoryId(spuDTO.getCid3());

        //suggestion
            //获取brandId
        List<String> suggest = new ArrayList<>();
        String bName = spuDTO.getBrandName();
        suggest.add(bName);
        String shortBName = StringUtils.substringBefore(bName, "（");

        //获取categoryName
        String cName = spuDTO.getCategoryName().split("/")[2];
        suggest.add(cName);
        suggest.add(shortBName+cName);
        suggest.add(cName+shortBName);
            //获取商品名称
        suggest.add(spuDTO.getName());
            //将suggest放入goods
        goods.setSuggestion(suggest);

        List<SkuDTO> skuDTOS = this.itemClient.querySkuBySpuId(spuDTO.getId());
        //image
        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(),","));

        //prices
        Set<Long> prices = new HashSet<>();

        Long sold = 0L;

        for (SkuDTO skuDTO : skuDTOS) {
            sold = skuDTO.getSold();
            prices.add(skuDTO.getPrice());
        }

        goods.setPrices(prices);

        //sold
        goods.setSold(sold);

        //specs
        List<Map<String,Object>> specs = new ArrayList<>();

        List<SpecParamDTO> list = this.itemClient.querySpecValues(spuDTO.getId(), true);
        list.forEach(specParamDTO ->{
            Map<String,Object> map = new HashMap<>();
            map.put("name",specParamDTO.getName());
            map.put("value",chooseSegment(specParamDTO));
            specs.add(map);
        });
        goods.setSpecs(specs);

        //updateTime
        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public void loadData() {
        createIndexAndMapping();
        //定义查询页数
        int page = 1;

        //创建while死循环，查询数据库中所有数据并导入elasticsearch
        while (true){

            //分页查询数据库中的信息
            PageDTO<SpuDTO> pageDTO = this.itemClient.queryPage(page, 50, null,
                    null, null, null);

            //没有数据跳出循环
            if(pageDTO.getTotalPage()==0){
                break;
            }

            //创建新的集合存放Goods信息
            List<Goods> list = new ArrayList<>();
            //将查询到的分页信息存储到新的集合并补全剩余信息

            List<Goods> goodsList = pageDTO
                    .getItems()
                    .stream()
                    .map(this::buildGoods)
                    .collect(Collectors.toList());

            //将从数据库中获取到的数据存入elasticsearch
            this.goodsRepository.saveAll(goodsList);

            //当前页数据查询结束，并将数据存入elasticsearch后页数加一，查询下一页数据
            page++;

            //如果当前页为最后一页，数据查询结束跳出循环
            if(page>pageDTO.getTotalPage()){
                break;
            }
        }
    }

    @Override
    public void saveGoodsById(Long spuId) {
        //用spuId查询到supDTO
        SpuDTO spuDTO = this.itemClient.queryGoodsById(spuId);

        //健壮性处理
        if(Objects.nonNull(spuDTO)){
            //使用buildGood方法获得Goods对象
            Goods goods = this.buildGoods(spuDTO);

            //将Goods对象存入elasticsearch
            this.goodsRepository.save(goods);
        }
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        this.goodsRepository.deleteById(spuId);
    }


}
